package com.atguigu.gmall.product.bloom.impl;

import com.atguigu.gmall.product.bloom.BloomOpsService;
import com.atguigu.gmall.product.bloom.SkuBloomDataQueryService;
import com.atguigu.gmall.product.service.SkuInfoService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BloomOpsServiceImpl implements BloomOpsService {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SkuInfoService skuInfoService;
    @Override
    public void rebuildBloom(String bloomName, SkuBloomDataQueryService skuBloomDataQueryService) {
        RBloomFilter<Object> oldBloomFilter = redissonClient.getBloomFilter(bloomName);
        //1、先准备一个新的布隆过滤器，所有东西初始化好
        String newBloomName = bloomName + "_new";
        RBloomFilter<Object> newBloomFilter = redissonClient.getBloomFilter(newBloomName);

        //2、拿到所有skuId
        //List<Long> allSkuId = skuInfoService.findAllSkuId();
        List list = skuBloomDataQueryService.queryData(); //动态获取
        //3、初始化新的布隆
        newBloomFilter.tryInit(5000000,0.00001);

        for (Object skuId : list) {
            //4、将所有的skuId放入新的布隆过滤器
            newBloomFilter.add(skuId);
        }

        //5、准备一个中间过滤器（两个布隆过滤器直接交换，大数据情况下导致redis直接卡死）
        oldBloomFilter.rename("temp_bloomFilter");//老布隆下线
        newBloomFilter.rename(bloomName);//新布隆上线

        //6、删除老布隆，和中间布隆交换
        oldBloomFilter.deleteAsync();
        redissonClient.getBloomFilter("temp_bloomFilter").deleteAsync();

    }
}
